<template>
	<view class="container">
		<view class="top-msg-list">
			<view class="top-msg"  @tap="toUrl(comment)">
				<view class="top-msg-badge">
					<image  src="/static/images/message/comment.jpg" class="top-msg-pic" mode="widthFix"></image>
					<tui-badge v-if="comment.num > 0" type="red" absolute :scaleRatio="0.8" translateX="40%" top="-2rpx">{{formatUnreadCount(comment.num)}}</tui-badge>
				</view>
				<view class="top-msg-type">评论</view>
			</view>
			<view class="top-msg"  @tap="toUrl(follow)" >
				<view class="top-msg-badge">
					<image  src="/static/images/message/follow.jpg" class="top-msg-pic" mode="widthFix"></image>
					<tui-badge v-if="follow.num > 0" type="red" absolute :scaleRatio="0.8" translateX="40%" top="-2rpx">{{formatUnreadCount(follow.num)}}</tui-badge>
				</view>
				<view class="top-msg-type">关注</view>
			</view>
			<view class="top-msg"  @tap="toUrl(like)">
				<view class="top-msg-badge">
					<image  src="/static/images/message/like.jpg" class="top-msg-pic" mode="widthFix"></image>
					<tui-badge v-if="like.num > 0" type="red" absolute :scaleRatio="0.8" translateX="40%" top="-2rpx">{{formatUnreadCount(like.num)}}</tui-badge>
				</view>
				<view class="top-msg-type">点赞</view>
			</view>
		</view>
		
		<block v-for="(item,index) in dialogues" :key="index">
			<tui-list-cell @click="jump(item)"  :unlined="false">
				<view class="tui-chat-item">
					<view class="tui-msg-box">
						<!--头像-->
						<image :src="item.avatar" class="tui-msg-pic" mode="widthFix"></image>
						<view class="tui-msg-item">
							<view class="tui-msg-name">{{item.nickname}}</view><!--昵称-->
							<view class="tui-msg-content">{{item.msg}}</view><!--消息-->
						</view>
					</view>
					<view class="tui-msg-right" :class="[item.level==3?'tui-right-dot':'']">
						<view class="tui-msg-time">{{item.timeText}}</view><!--时间-->
						<!--未读记录数-->
						<!-- <tui-badge :type="item.level==2?'gray':'danger'" :dot="item.level==3?true:false" v-if="item.msgNum>0">{{item.level!=3?item.msgNum:""}}</tui-badge> -->
						<tui-badge :type="'danger'"  v-if="item.msgNum>0">{{item.level!=3?item.msgNum:""}}</tui-badge>
					</view>
				</view>
			</tui-list-cell>
		</block>
		<view class="tui-safearea-bottom"></view>
	</view>
</template>


<script>
	import c from "@/utils/Constant.js"
	const systemNoticesUrl = "/pages/message/system-notices"
	import messageApi from '@/request/api/messageApi.js'
	import moment from "moment"
	import dateUtils from "@/utils/DateUtils.js"
	import noticeParser from "@/utils/NoticeParser.js"
	import userUtils from "@/utils/userUtils.js"
	import textUtils from "@/utils/TextUtils.js"
	import listUtils from "@/utils/ListUtils.js"
	import globalWebsocket from "@/request/websocket/GlobalWebsocket.js"
	export default {
		data() {
			return {
				current: 0,
				dialogues: [],
				weekStr:["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],
				comment:{
					messageType:c.action.REPLY,
					num:0,
					url:"/pages/message/reply-notices"
				},
				like:{
					messageType:c.action.LIKE,
					num:0,
					url:"/pages/message/like-notices"
				},
				follow:{
					messageType:c.action.FOLLOW,
					num:0,
					url:"/pages/message/follow-notices"
				},
				interval:null
			}
		},
		created() {
			this.refreshData();
			globalWebsocket.onmessage(this.onGlobalMessage)//监听全局通知socketServer发来的消息
		},
		methods: {
			//监听全局通知socketServer发来的消息
			onGlobalMessage(message){
				console.log("接收到全局通知")
				//当消息类型为1时，代表有新消息，刷新对话列表
				if(message.type == 1){
					this.refreshData();
				}
			},
			//跳转到对话对应的页面
			jump(dialogue){
				uni.navigateTo({
					url:dialogue.jumpUrl
				})
				dialogue.msgNum = 0;//当用户进入对话时，清空未读记录数
			},
			//查询用户的所有对话
			dialogueList(){
				messageApi.dialogueList().then((data)=>{
					if(data.code == 0){
						console.log(data.data)
						data.data.forEach((item)=>{
							if(item.userInfo != null){
								let formatDialogue = this.formatDialogue(item)
								this.setJumpUrl(item,formatDialogue)
								//this.dialogues.push(formatDialogue)
								this.pushDialogue(formatDialogue);
							}
						})
						//按对话的时间倒序排序
						this.dialogues = this.dialogues.sort((d1,d2)=>{
							let time1 = moment(d1.time).valueOf();
							let time2 = moment(d2.time).valueOf();
							return time2 - time1;
						})			
					}
				})
			},
			//将对话对象添加到数组中
			/**
			 * 判断对话是否已存在，存在的话,则替换
			 * 不存在则添加到集合中
			 */
			pushDialogue(formatDialogue){
				let index = this.dialogues.findIndex(item => item.id === formatDialogue.id);
				if(index != -1){
					this.dialogues.splice(index, 1)
				}
				this.dialogues.push(formatDialogue);
			},
			//将后端传来的对话格式化为前端需要的对话对象
			formatDialogue(dialogue){
				if(dialogue.userInfo.id == 1){
					dialogue.userInfo.nickname = "系统通知";
					dialogue.userInfo.avatar="/static/images/message/system.png";
					let content = noticeParser.parseContent(dialogue.lastMessage)
					dialogue.lastMessage.content = textUtils.beyondLimitSubStr(content,15,'...')
				}
				let formatDlg ={
					id:dialogue.userInfo.id,
					nickname:dialogue.userInfo.nickname,
					avatar:dialogue.userInfo.avatar,
					msg:dialogue.lastMessage.content,
					msgNum:this.formatUnreadCount(dialogue.unreadCount),
					timeText: this.getTimeText(dialogue.lastMessage.createTime),
					time:dialogue.lastMessage.createTime
				}
				return formatDlg;
			},
			formatUnreadCount(num){
				return num >= 99?'99+':num;			
			},
			
			/**  
			 * 消息时间显示
			 *   1、今天的消息就显示时分 例如: 12:35
			 *   2、昨天的消息就显示"昨天"
			 *   3、不是昨天的消息并且是本周的消息就显示星期 例如：星期二
			 *   4、今年的显示月日 例如：3月20日
			 *   6、其他的显示年月日 例如：2020/3/20
			 */
			getTimeText(time){
				let date = moment(time);
				let type = dateUtils.getRelativeTimeType(date)
				if(type == 1 || type==0){//今天的消息就显示时分 例如: 12:35
					return `${date.hour()}:${date.minute()}`
				}
				if(type == 2){//昨天的消息就显示"昨天"
					return "昨天";
				}
				if(type == 3){//不是昨天的消息并且是本周的消息就显示星期 例如：星期二
					return this.weekStr[date.day()];
				}
				if(type == 4 || type == 5){//今年的显示月日 例如：3月20日
					return `${date.month()+1}月${date.date()}日`;
				}
				//其他的显示年月日 例如：2020/3/20
				return `${date.year()}/${date.month()+1}/${date.date()}`;
			},
			//设置跳转的连接
			setJumpUrl(dialogue,formatDlg){
				let id = dialogue.userInfo.id
				if(id == 1){ //如果id为1，跳转到系统通知页面
					formatDlg["jumpUrl"] = systemNoticesUrl;
				}else if(dialogue.lastMessage.type == 8){ //如果消息类型为8，代表私聊，跳转到私聊页面
					formatDlg["jumpUrl"] = "/pages/chat/chat?id="+id
				}
			},
			//跳转页面，跳转到评论、关注、点赞这几个页面专用的方法
			toUrl(obj){
				userUtils.loginCheck().then(()=>{//检查是否登录再跳转
					uni.navigateTo({
						url:obj.url
					})
					obj.num = 0;
				})		
			},
			//设置未读记录数，关注、点赞、回复这几个专用的方法
			setUnread(obj){
				messageApi.unreadByType(obj.messageType).then((data)=>{
					if(data.code == 0){
						obj.num = data.unreadCount
					}
				})
			},
			refreshData(){
				this.dialogueList();
				this.setUnread(this.comment)
				this.setUnread(this.like)
				this.setUnread(this.follow)
			}
		},
		
		onPullDownRefresh: function() {
			uni.stopPullDownRefresh();
		}
	}
	
</script>

<style>

.container {
		padding-bottom: 100rpx
	}
	/**
	 * top,关注、点赞、回复等
	 */
	.top-msg-list {
		background-color: #fff;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex-wrap: wrap;
		font-size: 24rpx;
		color: #555;
		margin-bottom: 20rpx;
	}
	
	.top-msg {
		width: 20%;
		height: 118rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex-direction: column;
		padding-top: 30rpx;
	}
	.tui-category-img {
		height: 80rpx;
		width: 80rpx;
		display: block;
	}
	.top-msg-type {
		line-height: 24rpx;
	}
	
	
	.top-msg-pic {
		width: 100rpx;
		height: 100rpx;
	}
	
	.top-msg-badge {
		position: relative;
	}

	

	/*tabbar*/

	.tui-tabbar {
		width: 100%;
		position: fixed;
		display: flex;
		align-items: center;
		justify-content: space-between;
		z-index: 99999;
		background-color: #fff;
		height: 100rpx;
		left: 0;
		bottom: 0;
		padding-bottom: env(safe-area-inset-bottom);
	}

	.tui-safearea-bottom {
		width: 100%;
		height: env(safe-area-inset-bottom);
	}

	.tui-tabbar::before {
		content: '';
		width: 100%;
		border-top: 1rpx solid #d2d2d2;
		position: absolute;
		top: 0;
		left: 0;
		-webkit-transform: scaleY(0.5);
		transform: scaleY(0.5);
	}

	.tui-tabbar-item {
		flex: 1;
		width: 25%;
		display: flex;
		align-items: center;
		flex-direction: column;
		justify-content: space-between;
		font-size: 24rpx;
		color: #666;
		height: 80rpx;
	}

	.tui-ptop-4 {
		padding-top: 4rpx;
	}

	.tui-scale {
		font-weight: bold;
		transform: scale(0.8);
		transform-origin: center 100%;
		line-height: 30rpx;
	}

	.tui-item-active {
		color: #00c0fb !important;
	}

	/*tabbar*/

	.tui-chat-item {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.tui-msg-box {
		display: flex;
		align-items: center;
	}

	.tui-msg-pic {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		display: block;
		margin-right: 24rpx;
	}

	.tui-msg-item {
		max-width: 500rpx;
		min-height: 80rpx;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.tui-msg-name {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		font-size: 34rpx;
		line-height: 1;
		color: #262b3a;
	}

	.tui-msg-content {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		font-size: 28rpx;
		line-height: 1;
		color: #9397a4;
	}

	.tui-msg-right {
		max-width: 120rpx;
		height: 88rpx;
		margin-left: auto;
		text-align: right;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: flex-end;
	}

	.tui-msg-right.tui-right-dot {
		height: 76rpx;
		padding-bottom: 10rpx;

	}

	.tui-msg-time {
		width: 100%;
		font-size: 24rpx;
		line-height: 24rpx;
		color: #9397a4;
	}
</style>
